package com.cqc.config;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;

@Configuration
public class ElasticsearchConfig {

    /**
     * hosts 多个节点地址，如 "http://192.168.1.10:9200", "http://192.168.1.11:9200"
     */
    @Bean
    public ElasticsearchClient elasticsearchClient() throws UnknownHostException {
        HttpHost httpHost1 = new HttpHost(InetAddress.getByName("127.0.0.1"), 9200);
        // 凭证提供者（用于安全认证）
        String username = null;
        String password = null;
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        if (username != null && password != null) {
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
        }

        // 可选：配置连接超时、重试等
        RestClient restClient = RestClient.builder(httpHost1)
                .setHttpClientConfigCallback((HttpAsyncClientBuilder httpAsyncClientBuilder) -> {
                    httpAsyncClientBuilder.disableAuthCaching(); // 禁用认证缓存（某些版本需要）
                    return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                })
                .build();


        // 创建传输层和客户端
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        return new ElasticsearchClient(transport);
    }
}